package com.liqw.consumer.controller;

import com.liqw.consumer.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController{

    @Autowired
    ConsumerService service;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @GetMapping("/sayConsumer")
    public String sayConsumer() {
        return service.sayConsumer();
    }

    @GetMapping("/sayProvider")
    public String sayProvider(){
        // 通过spring cloud common中的负载均衡接口选取服务提供节点实现接口调用
        ServiceInstance serviceInstance = loadBalancerClient.choose("springcloud-provider");
        String url = serviceInstance.getUri() + "/sayProvider";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }
}
